package com.cdy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdy.entity.Admin;
import com.cdy.entity.Student;
import com.cdy.entity.Teacher;
import com.cdy.service.IAdminService;
import com.cdy.service.IStudentService;
import com.cdy.service.ITeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IAdminService iAdminService;
    @Autowired
    private IStudentService iStudentService;
    @Autowired
    private ITeacherService iTeacherService;

    @GetMapping("/login")
    public boolean loginIn(String name, String pwd, int role, HttpSession session){
        Object one=null;
        if(role==1){
            QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.eq("name",name).eq("pwd",pwd);
            one=iStudentService.getOne(studentQueryWrapper);
        }if(role==2){
            QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
            teacherQueryWrapper.eq("name",name).eq("pwd",pwd);
            one=iTeacherService.getOne(teacherQueryWrapper);
        }if(role==3){
            QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
            adminQueryWrapper.eq("name",name).eq("pwd",pwd);
            one=iAdminService.getOne(adminQueryWrapper);
        }
        if (one!=null){
            session.setAttribute("one",one);
        }
        return one !=null;

    }
    //退出
    @GetMapping("/")
    public void tuiChu( HttpSession session){
        session.invalidate();
    }

    //修改密码
    @PutMapping("/xg")
    public void updatePassword(int role,String pwd,HttpSession session){
        if(role==1){
            Student student = (Student)session.getAttribute("one");
            student.setPwd(pwd);
            iStudentService.updateById(student);
            session.setAttribute("one",student);
        }if(role==2){
            Teacher teacher = (Teacher)session.getAttribute("one");
            teacher.setPwd(pwd);
            iTeacherService.updateById(teacher);
            session.setAttribute("one",teacher);
        }if(role==3){
            Admin admin = (Admin)session.getAttribute("one");
            admin.setPwd(pwd);
            iAdminService.updateById(admin);
            session.setAttribute("one",admin);
        }

    }
}
